﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using System.Threading;
using System.Collections;

namespace P_SetUp
{
    public partial class Form_M : Form
    {
        public Form_M()
        {
            InitializeComponent();
        }
        #region
        private Mydb MyDb;
        private MySqlDb mySqlDb;
        private bool IsBegin;
        private bool IsStop;
        private string VersionNo = "V 2.6";
        private DataTable GridTable,GridColumnTable;

        #endregion

        #region 私有方法
        private Class_File Filer;

        private void UpdateGridVersion()
        {
            MyDb.pub_ExecBySqlText(@"update Sys_Version
                set VersNo=GETDATE()
                where LibName='Sel_Sys_GridCols_LV'");
        }
        private void ReadFromXml(string XMLFile)
        {
            DataTable XMLTable = new DataTable("ConStrTable");
            if (System.IO.File.Exists(XMLFile))
            {
                XMLTable.ReadXml(XMLFile);
                DataView DefaultView = new DataView();
                DefaultView = XMLTable.DefaultView;
                DefaultView.Sort = "Index";
                this.comboBox1.Items.Clear();
                foreach (DataRowView Row in DefaultView)
                    this.comboBox1.Items.Add(Row["ConStr"].ToString());

                this.comboBox1.SelectedIndex = this.comboBox1.Items.Count > 0 ? 0 : -1;
            }
            XMLTable.Dispose();
        }
        private void DeleteFromXml(string ConStr)
        {
            Class_File File = new Class_File();
            string XMLFile = Application.StartupPath + "\\ConStr.xml";
            DataTable XMLTable = new DataTable("ConStrTable");
            if (System.IO.File.Exists(XMLFile))
            {
                XMLTable.ReadXml(XMLFile);
                bool Finder = false;
                foreach (DataRow Row in XMLTable.Rows)
                {
                    if (Row["ConStr"].ToString() == ConStr)
                    {
                        Row.Delete();
                        Finder = true;
                    }
                    if (Finder)
                        break;
                }
            }
            XMLTable.AcceptChanges();
            XMLTable.WriteXml(XMLFile, XmlWriteMode.WriteSchema);
            XMLTable.Dispose();
        }
        private void WriteIntoXml(string ConStr)
        {
            Class_File File = new Class_File();
            string XMLFile = Application.StartupPath + "\\ConStr.xml";
            DataTable XMLTable = new DataTable("ConStrTable");
            if (System.IO.File.Exists(XMLFile))
            {
                XMLTable.ReadXml(XMLFile);
                bool Finder = false;
                int Counter = 1;
                foreach (DataRow Row in XMLTable.Rows)
                {
                    Row.BeginEdit();
                    if (Row["ConStr"].ToString() == ConStr)
                    {
                        Row["Index"] = 0;
                        Finder = true;
                    }
                    else
                        Row["Index"] = Counter++;
                    Row.EndEdit();
                }
                if (!Finder)
                {
                    DataRow NewRow = XMLTable.NewRow();
                    NewRow["Index"] = 0;
                    NewRow["ConStr"] = ConStr;
                    XMLTable.Rows.Add(NewRow);
                }
            }
            else
            {
                DataColumn[] Keys = new DataColumn[1];
                DataColumn ConStrCol = new DataColumn();
                ConStrCol.ColumnName = "ConStr";
                ConStrCol.DataType = Type.GetType("System.String");
                Keys[0] = ConStrCol;
                XMLTable.Columns.Add(ConStrCol);
                DataColumn IndexCol = new DataColumn();
                IndexCol.ColumnName = "Index";
                IndexCol.DataType = Type.GetType("System.Int32");
                XMLTable.Columns.Add(IndexCol);
                XMLTable.PrimaryKey = Keys;

                DataRow NewRow = XMLTable.NewRow();
                NewRow["Index"] = 0;
                NewRow["ConStr"] = ConStr;
                XMLTable.Rows.Add(NewRow);
            }
            XMLTable.AcceptChanges();
            XMLTable.WriteXml(XMLFile, XmlWriteMode.WriteSchema);
            XMLTable.Dispose();
        }
        private void SelectToText()
        {
            this.gridControl3.Enabled = false;
            this.tabControl5.SelectedIndex = 1;
            this.progressBar4.Visible = true;
            this.progressBar4.Maximum = this.gridView3.DataRowCount;
            this.textBox6.Clear();
            StringBuilder FieldName = new StringBuilder();
            StringBuilder FieldValue = new StringBuilder();
            for (int Index = 0; Index < this.gridView3.Columns.Count; Index++)
                FieldName.Append("," + this.gridView3.Columns[Index].FieldName);
            for (int Index = 0; Index < this.gridView3.DataRowCount; Index++)
            {
                FieldValue.Clear();
                DataRow CurRow = this.gridView3.GetDataRow(Index);
                this.textBox6.AppendText(string.Format(@"Insert Into {0} ({1})", this.textBox2.Text.Trim(), FieldName.ToString().Substring(1)));
                this.textBox6.AppendText("\r\nValues (");
                for (int ColIndex = 0; ColIndex < this.gridView3.Columns.Count; ColIndex++)
                {
                    FieldValue.Append(",");
                    if (this.IsAddBeginEnd(this.gridView3.Columns[ColIndex].ColumnType.ToString()))
                        FieldValue.Append("'");
                    string FieldContent = CurRow[ColIndex].ToString();
                    if (FieldContent == "True")
                        FieldContent = "1";
                    if (FieldContent == "False")
                        FieldContent = "0";
                    FieldValue.Append(FieldContent);
                    if (this.IsAddBeginEnd(this.gridView3.Columns[ColIndex].ColumnType.ToString()))
                        FieldValue.Append("'");
                }
                this.textBox6.AppendText(FieldValue.ToString().Substring(1));
                this.textBox6.AppendText(")\r\nGO\r\n");
                this.progressBar4.Value = Index + 1;
                Application.DoEvents();
                Thread.Sleep(0);
            }
            FieldName.Length = 0;
            FieldValue.Length = 0;
            this.progressBar4.Visible = false;
            this.gridControl3.Enabled = true;
        }
        private void SelectToData()
        {
            try
            {
                if (this.textBox2.Text.Trim().Length > 0)
                {
                    if (this.textBox5.Text.Trim().Length > 0)
                    {
                        this.gridView3.Columns.Clear();
                        this.gridControl3.DataSource = MyDb.GetDataTable(this.textBox5.Text.Trim());
                        this.tabControl5.SelectedIndex = 0;
                    }
                }
                else
                    MessageBox.Show("请先选择用户表");
            }
            catch
            {
                MessageBox.Show("SQL语句有问题，请重写！");
            }
        }
        private bool IsAddBeginEnd(string FieldType)
        {
            bool RetureValue;
            switch (FieldType)
            {
                case "System.Int32":
                    RetureValue = false;
                    break;
                case "System.DateTime":
                    RetureValue = false;
                    break;
                case "System.Decimal":
                    RetureValue = false;
                    break;
                default:
                    RetureValue = true;
                    break;
            }
            return RetureValue;
        }
        /// <summary>
        /// 保存GRID列设置
        /// </summary>
        /// <param name="Corpid">企业ID</param>
        /// <param name="Pageid">页面ID</param>
        /// <param name="GridView">指定GRIDVIEW</param>
        private void SaveGirdColumnInfo(string Corpid,string Pageid,GridView GridView)
        {
            Filer = new Class_File();
            string CurrentPath = System.Environment.CurrentDirectory + "\\" + Pageid;
            if (!Filer.SelfDirectoryExists(CurrentPath))
                Filer.CreateFolder(CurrentPath);
            GridView.SaveLayoutToXml(CurrentPath + "\\" + Corpid + ".xml");
        }
        /// <summary>
        /// 从XML中设置GRID列
        /// </summary>
        /// <param name="Corpid">企业ID</param>
        /// <param name="Pageid">页面ID</param>
        /// <param name="GridView">指定GRIDVIEW</param>
        private void RestoreGridColumnInfo(string Corpid, string Pageid, GridView GridView)
        {
            Filer = new Class_File();
            string AllPathName = System.Environment.CurrentDirectory + "\\" + Pageid + "\\" + Corpid + ".xml";
            if (Filer.SelfFileExists(AllPathName))
                GridView.RestoreLayoutFromXml(AllPathName);
        }

        private void DeleteGridColumn()
        {
            if (MessageBox.Show("您要删除该条数据吗？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                string ID = this.gridView2.GetFocusedRowCellValue("ID").ToString();
                if (ID != null)
                {
                    string UpdateSql = string.Format(@"Delete from Sys_GridCols
                        Where ID='{0}'", ID);
                    MyDb.pub_ExecBySqlText(UpdateSql);
                    DataRowView Del = (DataRowView)this.gridView2.GetFocusedRow();
                    Del.Delete();
                    this.GridColumnTable.AcceptChanges();
                    this.label2.Text = System.DateTime.Now.ToString("hh-mm-ss") + ":有1条Grid列数据被删除";
                    UpdateGridVersion();
                }
            }
        }

        private bool AddGridColu(string ID, string PareID, string Num, string SortNo, string FieldName, string FieldType, string TitleRemark)
        {
            string FormatStr = "";
            string ColuWidth = "140";
            string ColuAlign = "0";
            switch (FieldType)
            {
                case "smalldatetime":
                    FormatStr = "yyyy-MM-dd";
                    ColuWidth = "80";
                    break;
                case "smallint":
                    FormatStr = "{0:0.00}";
                    ColuWidth = "80";
                    ColuAlign = "1";
                    break;
                case "datetime":
                    FormatStr = "yyyy-MM-dd hh:mm:ss";
                    ColuWidth = "120";
                    break;
                case "decimal":
                    FormatStr = "{0:0.00}";
                    ColuWidth = "80";
                    ColuAlign = "1";
                    break;
                case "float":
                    FormatStr = "{0:0.00}";
                    ColuWidth = "80";
                    ColuAlign = "1";
                    break;
                case "bit":
                    ColuWidth = "40";
                    break;
                default:
                    break;
            }
            string Sql = string.Format(@"Insert Into Sys_GridCols(ID,PareID,Num,Name,WorkID,WorkTime,StopSign,Remark,TitleRemark
                ,SortNo,FieldName,FieldType,EditColu,FormatStr,FixedColu,IsVisi,ColuWidth,IsFilter
                ,ColuTitleAlign,ColuAlign,IsRead,IsAutoFilt,IsNull,IsOne,IsGroup,IsSort,IsGroupSum,Type,BSColValue,BSChkOne
                ,BSSubmit,AllowGroup,FieldLen)
                Values('{0}','{1}','','{2}','',GETDATE(),'0','','{6}'
                ,{3},'{4}','{5}','0','{7}','','{10}',{8},'1'
                ,0,{9},'1','0','0','0','0','none','0','gridcolu','',''
                ,'1','1','1000')", ID, PareID, Num, SortNo, FieldName, FieldType, TitleRemark, FormatStr, ColuWidth, ColuAlign, FieldName.ToLower() == "id" ? "0":"1");
            MyDb.pub_ExecBySqlText(Sql);
            return true;
        }
        /// <summary>
        /// 是否两边加单引号
        /// </summary>
        /// <param name="FieldType"></param>
        /// <returns></returns>
        private bool IsAddZone(string FieldType)
        {
            string FieldTypeList = "text,varchar,char,String,nvarchar,bit,datetime";
            return FieldTypeList.IndexOf(FieldType) > -1 ? true : false;
        }
        private void SetUpText(TextBox TextBoxOr)
        {
            TextBoxOr.BackColor = System.Drawing.SystemColors.Info;
            TextBoxOr.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            TextBoxOr.Multiline = true;
            TextBoxOr.ScrollBars = System.Windows.Forms.ScrollBars.Both;
        }
        private void GetTableField(string TableName)
        {
            this.tabControl2.SelectedIndex = 1;
            this.IsBegin = false;
            DataTable FieldTable = new DataTable();
            string Sql;
            switch (this.radioGroup1.SelectedIndex)
            {
                case 0:
                    Sql = string.Format(@"SELECT
            column_name AS '字段名',
            CASE WHEN  left(COLUMN_TYPE, LOCATE('(', COLUMN_TYPE) - 1) = '' THEN COLUMN_TYPE ELSE  left(COLUMN_TYPE, LOCATE('(', COLUMN_TYPE) - 1) END   AS '类型',
            CAST(SUBSTRING(COLUMN_TYPE, LOCATE('(', COLUMN_TYPE) + 1, LOCATE(')', COLUMN_TYPE) - LOCATE('(', COLUMN_TYPE) - 1) AS signed) AS '长度',
            CASE WHEN LOCATE(',',COLUMN_TYPE) = 0 THEN '' ELSE SUBSTRING(COLUMN_TYPE,LOCATE(',',COLUMN_TYPE)+1,LOCATE(')',COLUMN_TYPE) - LOCATE(',',COLUMN_TYPE) - 1) END as '小数位数',
            column_default  AS  `默认值`,
            column_comment  AS  `字段说明`,
            CASE WHEN COLUMN_KEY = 'PRI'
            THEN true ELSE false END AS `主键`,
            CASE WHEN EXTRA = 'auto_increment' THEN true ELSE false END as '标识',
            CASE WHEN is_nullable = 'YES'
            THEN '是' ELSE '' END AS `允许空`
            FROM
            Information_schema.columns
            where TABLE_NAME = '{0}' and  TABLE_SCHEMA = (select database()) ORDER BY TABLE_NAME", TableName);
                    FieldTable = mySqlDb.GetDataTable(Sql);
                    break;
                case 1:
                    Sql = string.Format(@"select  字段序号 = a.colorder ,字段名 = a.name ,字段说明 = isnull(g.[value], ''),
            允许空 = case when a.isnullable = 1 then '是' else '' end ,
            默认值 = isnull(e.text, '') ,类型 = b.name ,
            标识 = case when columnproperty(a.id, a.name, 'IsIdentity') = 1 then '是'
            else '' end ,
            主键 = case when exists ( select  1
            from sysobjects
	            where   xtype = 'PK' and name in (select    name
	            from sysindexes
	            where indid in (select    indid
	            from sysindexkeys
	            where id = a.id and colid = a.colid)) 
            ) then '是' else '' end ,
            占用字节数 = a.length ,长度 = columnproperty(a.id, a.name, 'PRECISION') ,
            小数位数 = isnull(columnproperty(a.id, a.name, 'Scale'), 0) 
            from syscolumns a
            left join systypes b on a.xusertype = b.xusertype
            inner join sysobjects d on a.id = d.id and d.xtype in('U','V') and d.name <> 'dtproperties'
            left join syscomments e on a.cdefault = e.id
            left join sys.extended_properties g on a.id = g.major_id and a.colid = g.minor_id
            left join sys.extended_properties f on d.id = f.major_id and f.minor_id = 0
            where d.name='{0}'
            order by a.id,a.colorder", TableName);
                    FieldTable = MyDb.GetDataTable(Sql);
                    break;
                default:
                    break;
            }

            if ((FieldTable != null) && (FieldTable.Rows.Count > 0))
            {
                this.checkBox1.Checked = true;
                this.listView1.Items.Clear();
                int Counter = 1;
                this.progressBar1.Value = 0;
                this.progressBar1.Minimum = 0;
                this.progressBar1.Maximum = FieldTable.Rows.Count;
                this.progressBar1.Visible = true;
                this.label6.Text = "0";
                foreach (DataRow Row in FieldTable.Rows)
                {
                    string FieldName = Row["字段名"].ToString();
                    string FieldContent = Row["字段说明"].ToString().Trim();
                    string FieldType = Row["类型"].ToString();
                    string Length = Row["长度"].ToString();
                    string SmallNumlength = Row["小数位数"].ToString();
                    string IsNull = Row["允许空"].ToString();
                    string DefaultValue = Row["默认值"].ToString();
                    string IsKey = Row["主键"].ToString();
                    string IsRemark = Row["标识"].ToString();
                    this.AddFieldToListView(FieldName, FieldContent, FieldType, Length, SmallNumlength, IsNull, DefaultValue, IsKey, IsRemark);
                    this.progressBar1.Value = Counter++;
                    this.label6.Text = "共" + Counter.ToString() + "列";
                    Application.DoEvents();
                    Thread.Sleep(0);
                }
                Sql = string.Format("select count(*) as Counter from {0}", TableName);
                switch (this.radioGroup1.SelectedIndex)
                {
                    case 0:
                        this.label6.Text += "," + mySqlDb.GetDataTable(Sql).Rows[0]["Counter"].ToString() + "条数据";
                        break;
                    case 1:
                        this.label6.Text += "," + MyDb.GetDataTable(Sql).Rows[0]["Counter"].ToString() + "条数据";
                        break;
                    default:
                        break;
                }

                this.progressBar1.Visible = false;
            }
            FieldTable.Dispose();
            this.IsBegin = true;
        }
        private void SetListView()
        {
            this.listView1.FullRowSelect = true;
            this.listView1.GridLines = true;
            this.listView1.View = View.Details;
            this.listView1.CheckBoxes = true;
            this.listView1.MultiSelect = false;
        }
        private void SetGrid(GridView P_view,GridControl P_Grid)
        {
            #region 设置GRID导航栏
            P_view.OptionsView.ShowGroupPanel = true;
            P_view.OptionsView.ShowAutoFilterRow = true;
            P_view.Appearance.OddRow.BackColor = Color.Beige;
            P_view.OptionsView.EnableAppearanceOddRow = true;
            P_view.OptionsView.ColumnAutoWidth = false;
            P_view.OptionsCustomization.AllowGroup = true;

            P_Grid.UseEmbeddedNavigator = true;
            P_Grid.EmbeddedNavigator.TextStringFormat = "第{0}条,共{1}条";
            P_Grid.EmbeddedNavigator.Buttons.Edit.Visible = false;
            if (P_Grid.EmbeddedNavigator.Buttons.Edit.Visible)
                P_Grid.EmbeddedNavigator.Buttons.Edit.Hint = "开始修改";
            P_Grid.EmbeddedNavigator.Buttons.CancelEdit.Visible = false;
            if (P_Grid.EmbeddedNavigator.Buttons.CancelEdit.Visible)
                P_Grid.EmbeddedNavigator.Buttons.CancelEdit.Hint = "撤消修改";
            P_Grid.EmbeddedNavigator.Buttons.Append.Visible = false;
            if (P_Grid.EmbeddedNavigator.Buttons.Append.Visible)
                P_Grid.EmbeddedNavigator.Buttons.Append.Hint = "开始添加";
            P_Grid.EmbeddedNavigator.Buttons.EndEdit.Visible = false;
            if (P_Grid.EmbeddedNavigator.Buttons.EndEdit.Visible)
                P_Grid.EmbeddedNavigator.Buttons.EndEdit.Hint = "提交修改";
            P_Grid.EmbeddedNavigator.Buttons.Remove.Visible = false;
            if (P_Grid.EmbeddedNavigator.Buttons.Remove.Visible)
                P_Grid.EmbeddedNavigator.Buttons.Remove.Hint = "开始删除";
            P_Grid.EmbeddedNavigator.Buttons.First.Visible = true;
            if (P_Grid.EmbeddedNavigator.Buttons.First.Visible)
                P_Grid.EmbeddedNavigator.Buttons.First.Hint = "首条";
            P_Grid.EmbeddedNavigator.Buttons.Next.Visible = true;
            if (P_Grid.EmbeddedNavigator.Buttons.Next.Visible)
                P_Grid.EmbeddedNavigator.Buttons.Next.Hint = "下一条";
            P_Grid.EmbeddedNavigator.Buttons.Last.Visible = true;
            if (P_Grid.EmbeddedNavigator.Buttons.Last.Visible)
                P_Grid.EmbeddedNavigator.Buttons.Last.Hint = "末条";
            P_Grid.EmbeddedNavigator.Buttons.NextPage.Visible = true;
            if (P_Grid.EmbeddedNavigator.Buttons.NextPage.Visible)
                P_Grid.EmbeddedNavigator.Buttons.NextPage.Hint = "下一页";
            P_Grid.EmbeddedNavigator.Buttons.PrevPage.Visible = true;
            if (P_Grid.EmbeddedNavigator.Buttons.PrevPage.Visible)
                P_Grid.EmbeddedNavigator.Buttons.PrevPage.Hint = "上一页";
            P_Grid.EmbeddedNavigator.Buttons.Prev.Visible = true;
            if (P_Grid.EmbeddedNavigator.Buttons.Prev.Visible)
                P_Grid.EmbeddedNavigator.Buttons.Prev.Hint = "上一条";
            #endregion
        }
        private bool ConnectDataBase()
        {
            try
            {
                switch (this.radioGroup1.SelectedIndex)
                {
                    case 0:
                        mySqlDb = new MySqlDb(this.comboBox1.Text);
                        break;
                    case 1:
                        MyDb = new Mydb(this.comboBox1.Text);
                        break;
                    default:
                        break;
                }
                return true;
            }
            catch
            {
                MessageBox.Show("数据连接出错，请与系统管理员联系！");
                return false;
            }
        }
        private void IniForm()
        {
            IsBegin = false;
            IsStop = false;
            EnableButton(false);
            this.comboBox1.SelectedIndex = 0;
            this.comboBox1.Width = this.panel9.Width - 8;
            this.Text += VersionNo;
            this.progressBar1.Visible = false;
            this.progressBar2.Visible = false;
            this.progressBar3.Visible = false;
            this.progressBar4.Visible = false;
            SetUpText(this.Select_Text);
            SetUpText(this.Insert_Text);
            SetUpText(this.Update_Text);
            SetUpText(this.Delete_Text);
            SetUpText(this.Data_Text);
            SetUpText(this.textBox6);
            this.button19.Enabled = false;
            ReadFromXml(Application.StartupPath + "\\ConStr.xml");
        }
        private void EnableButton(bool IsEnable)
        {
            this.GetTable_B.Enabled = IsEnable;
            this.button2.Enabled = IsEnable;
            this.button3.Enabled = IsEnable;
            this.button4.Enabled = IsEnable;
            this.button5.Enabled = IsEnable;
            this.button6.Enabled = IsEnable;
            this.button7.Enabled = IsEnable;
            this.button8.Enabled = IsEnable;
            this.button9.Enabled = IsEnable;
            this.button10.Enabled = IsEnable;
            this.button11.Enabled = IsEnable;
            this.button12.Enabled = IsEnable;
            this.button13.Enabled = IsEnable;
            this.button14.Enabled = IsEnable;
            this.button15.Enabled = IsEnable;
            this.button16.Enabled = IsEnable;
            this.button17.Enabled = IsEnable;
            this.button18.Enabled = IsEnable;
            this.button19.Enabled = IsEnable;
            this.button20.Enabled = IsEnable;
            this.button21.Enabled = IsEnable;
            this.button22.Enabled = IsEnable;
            this.button23.Enabled = IsEnable;
            this.button24.Enabled = IsEnable;
            this.button25.Enabled = IsEnable;
        }
        private void GetUseTable()
        {
            string Str;
            DataTable UseTable = new DataTable("UseTable");
            switch (this.radioGroup1.SelectedIndex)
            {
                case 0:
                    Str = @"select TABLE_NAME as TableName
                        ,TABLE_COMMENT as TableRemark 
                        from information_schema.tables
                        where  TABLE_SCHEMA=(select database())  AND TABLE_TYPE='BASE TABLE'
                        ORDER BY TABLE_NAME";
                    UseTable = mySqlDb.GetDataTable(Str);
                    break;
                case 1:
                    Str = string.Format(@"select d.[name] as TableName
                ,isnull(f.value, '') as TableRemark
                from sysobjects as d
                left join sys.extended_properties f on d.id = f.major_id and f.minor_id = 0
                where d.xtype in('u','V')
                order by d.xtype,d.[name]");
                    UseTable = MyDb.GetDataTable(Str);
                    break;
                default:
                    break;
            }

            for (int Index = 0; Index < UseTable.Rows.Count; Index++)
            {
                this.TableName_L.Items.Add(UseTable.Rows[Index]["TableName"].ToString());
                this.listBox1.Items.Add(UseTable.Rows[Index]["TableRemark"].ToString());
            }
            UseTable.Dispose();
        }
        private void GetGridColumnInfo(string GridID)
        {
            if (GridID != null)
            {
                GridColumnTable = new DataTable();
                string Sql = string.Format(@"select ID,Num,Name,WorkID,WorkTime,StopSign,Remark,TitleRemark,SortNo
                ,FieldName,FieldType,EditColu,FormatStr,FixedColu,IsVisi,ColuWidth,IsFilter,ColuTitleAlign,ColuAlign
                ,IsRead,IsAutoFilt,[IsNull],IsOne,IsGroup,IsSort,IsGroupSum,BSColValue,BSChkOne,BSSubmit,AllowGroup,FieldLen 
                from Sys_GridCols
                where [Type]='gridcolu' and PareID='{0}'
                order by SortNo", GridID);
                GridColumnTable = MyDb.GetDataTable(Sql);
            }
        }
        
        /// <summary>
        /// 得到GRID主表信息
        /// </summary>
        /// <returns></returns>
        private void GetGridInfo()
        {
            GridTable = new DataTable();
            string Sql = @"select Grid.ID
                ,Grid.[Name] as GridName,Grid.TitleRemark,Grid.FixedColu,Grid.AllowGroup
                ,Grid.IsRead,Grid.IsAutoFilt,Grid.IsGroup,Grid.IsFilter
                from Sys_GridCols as Grid
                where Grid.[Type]= 'grid'
                order by Grid.ID";
            GridTable = MyDb.GetDataTable(Sql).Copy();
        }
        private void UpdateVersion(string AA)
        {
            //AA='Sel_Sys_GridCols_LV'
            string UpdateStr = string.Format(@"update Sys_Version
                set VersNo= GETDATE()
                where LibName='{0}'", AA);
            MyDb.pub_ExecBySqlText(UpdateStr);
        }
        /// <summary>
        /// 增加一个GRID
        /// </summary>
        /// <returns></returns>
        private bool AddGrid()
        {
            bool IsOk;
            string ID = MyDb.pub_GetCounterId("AA");
            string InsertSql = string.Format(@"insert into Sys_GridCols(
                Name,TitleRemark,FixedColu,AllowGroup,IsRead,IsAutoFilt,IsGroup,IsFilter,ID,PareId,Num,IsSort,IsGroupSum,Type)
                values('Defaul_Grid','','数据拖拉分组区','0','0','1','0','1','{0}','-1','',0,'0','grid')", ID);
            IsOk = MyDb.pub_ExecBySqlText(InsertSql);
            if (IsOk)
            {
                this.gridView1.AddNewRow();
                DataRow Row = this.gridView1.GetFocusedDataRow();
                Row.BeginEdit();
                Row["ID"] = ID;
                Row["GridName"] = "Defaul_Grid";
                Row["TitleRemark"] = "";
                Row["FixedColu"] = "数据拖拉分组区";
                Row["AllowGroup"] = "False";
                Row["IsRead"] = "False";
                Row["IsAutoFilt"] = "True";
                Row["IsGroup"] = "False";
                Row["IsFilter"] = "True";
                Row.EndEdit();
            }

            return IsOk;
        }
        private void EditGridColumn()
        {
            if (this.GridColumnTable.GetChanges() != null)
            {
                DataTable EditTable = new DataTable();
                EditTable = this.GridColumnTable.GetChanges();
                string UpdateSql;
                int IsUpdate = 0;
                for (int Index = 0; Index < EditTable.Rows.Count; Index++)
                {
                    DataRow Row = EditTable.Rows[Index];
                    if (Row.RowState == DataRowState.Modified)
                    {
                        string TitleRemark = EditTable.Rows[Index]["TitleRemark"].ToString();
                        string FieldName = EditTable.Rows[Index]["FieldName"].ToString();
                        string SortNo = EditTable.Rows[Index]["SortNo"].ToString();
                        string ID = EditTable.Rows[Index]["ID"].ToString();
                        string FieldType = EditTable.Rows[Index]["FieldType"].ToString();
                        string FormatStr = EditTable.Rows[Index]["FormatStr"].ToString();
                        string Name = EditTable.Rows[Index]["Name"].ToString();
                        string FixedColu = EditTable.Rows[Index]["FixedColu"].ToString();
                        string IsVisi = EditTable.Rows[Index]["IsVisi"].ToString();
                        string ColuWidth = EditTable.Rows[Index]["ColuWidth"].ToString();
                        string IsGroupSum = EditTable.Rows[Index]["IsGroupSum"].ToString();
                        string ColuTitleAlign = EditTable.Rows[Index]["ColuTitleAlign"].ToString();
                        string ColuAlign = EditTable.Rows[Index]["ColuAlign"].ToString();
                        string IsRead = EditTable.Rows[Index]["IsRead"].ToString();
                        string IsAutoFilt = EditTable.Rows[Index]["IsAutoFilt"].ToString();
                        string IsSort = EditTable.Rows[Index]["IsSort"].ToString();
                        string IsNull = EditTable.Rows[Index]["IsNull"].ToString();
                        string AllowGroup = EditTable.Rows[Index]["AllowGroup"].ToString();
                        string BSChkOne = EditTable.Rows[Index]["BSChkOne"].ToString();
                        string BSColValue = EditTable.Rows[Index]["BSColValue"].ToString();
                        string BSSubmit = EditTable.Rows[Index]["BSSubmit"].ToString();
                        UpdateSql = string.Format(@"Update Sys_GridCols
                            Set TitleRemark='{0}',FieldName='{1}',SortNo='{2}',FieldType='{3}',FormatStr='{4}'
                            ,Name='{5}',FixedColu='{6}',IsVisi='{7}',ColuWidth={8},IsGroupSum='{9}'
                            ,ColuTitleAlign={10},ColuAlign='{11}',IsRead='{12}',IsAutoFilt='{13}'
                            ,IsSort='{14}',IsNull='{15}',AllowGroup='{16}'
                            ,BSChkOne='{17}',BSColValue='{18}',BSSubmit='{19}'
                            Where ID='{20}'", TitleRemark, FieldName, SortNo, FieldType, FormatStr
                                            , Name, FixedColu, IsVisi, ColuWidth, IsGroupSum, ColuTitleAlign, ColuAlign, IsRead, IsAutoFilt, IsSort, IsNull, AllowGroup, BSChkOne, BSColValue, BSSubmit, ID);
                        IsUpdate += MyDb.pub_ExecBySqlText(UpdateSql) ? 1 : 0;
                    }
                }
                EditTable.Dispose();
                if (IsUpdate > 0)
                {
                    this.GridColumnTable.AcceptChanges();
                    this.label3.Text = System.DateTime.Now.ToString("hh-mm-ss") + ":有" + IsUpdate.ToString() + "条数据被修改";
                    UpdateGridVersion();
                }
            }
            else
                this.label3.Text = System.DateTime.Now.ToString("hh-mm-ss") + ":未找到需修改的数据";
        }
        private void EditGrid()
        {
            if (this.GridTable.GetChanges() != null)
            {
                DataTable EditTable = new DataTable();
                EditTable = this.GridTable.GetChanges();
                string UpdateSql;
                int IsUpdate = 0;
                for (int Index = 0; Index < EditTable.Rows.Count; Index++)
                {
                    DataRow Row = EditTable.Rows[Index];
                    if (Row.RowState == DataRowState.Modified)
                    {
                        string ID = EditTable.Rows[Index]["ID"].ToString();
                        string Name = EditTable.Rows[Index]["GridName"].ToString();
                        string TitleRemark = EditTable.Rows[Index]["TitleRemark"].ToString();
                        string FixedColu = EditTable.Rows[Index]["FixedColu"].ToString();
                        string AllowGroup = EditTable.Rows[Index]["AllowGroup"].ToString() == "True" ? "1" : "0";
                        string IsRead = EditTable.Rows[Index]["IsRead"].ToString() == "True" ? "1" : "0";
                        string IsAutoFilt = EditTable.Rows[Index]["IsAutoFilt"].ToString() == "True" ? "1" : "0";
                        string IsGroup = EditTable.Rows[Index]["IsGroup"].ToString() == "True" ? "1" : "0";
                        string IsFilter = EditTable.Rows[Index]["IsFilter"].ToString() == "True" ? "1" : "0";
                        UpdateSql = string.Format(@"Update Sys_GridCols
                            set Name='{0}',TitleRemark='{1}',FixedColu='{2}',AllowGroup='{3}'
                            ,IsRead='{4}',IsAutoFilt='{5}',IsGroup='{6}',IsFilter='{7}'
                            Where ID='{8}'", Name, TitleRemark, FixedColu, AllowGroup
                                , IsRead, IsAutoFilt, IsGroup, IsFilter, ID);
                        IsUpdate += MyDb.pub_ExecBySqlText(UpdateSql) ? 1 : 0;
                    }
                }
                EditTable.Dispose();
                if (IsUpdate > 0)
                {
                    this.GridTable.AcceptChanges();
                    this.label2.Text = System.DateTime.Now.ToString("hh-mm-ss") + ":有" + IsUpdate.ToString() + "条数据被修改";
                    UpdateGridVersion();
                }
            }
            else
                this.label2.Text = System.DateTime.Now.ToString("hh-mm-ss") + ":未找到需修改的数据";
        }
        /// <summary>
        /// 增加指定表字段信息
        /// </summary>
        /// <param name="FieldName">字段名</param>
        /// <param name="FieldContent">含意</param>
        /// <param name="FieldType">字段类型</param>
        /// <param name="DefaultValue">默认值</param>
        /// <param name="Length">字段长度</param>
        /// <param name="IsNull">是否能为空</param>
        /// <param name="IsNull">是否为主键</param>
        /// <param name="IsNull">是否为标识</param>
        private void AddFieldToListView(string FieldName, string FieldContent, string FieldType, string Length, string SmallNumlength, string IsNull, string DefaultValue, string IsKey, string IsRemark)
        {
            ListViewItem Item = new ListViewItem();
            Item.ImageIndex = 1;
            Item.Text = FieldName;
            Item.SubItems.Add(FieldContent);
            Item.SubItems.Add(FieldType);
            Item.SubItems.Add(Length);
            Item.SubItems.Add(SmallNumlength);
            Item.SubItems.Add(IsNull);
            Item.SubItems.Add(DefaultValue);
            Item.SubItems.Add(IsKey);
            Item.SubItems.Add(IsRemark);
            Item.Checked = true;
            this.listView1.Items.Add(Item);
        }
        private void ChangeListViewChecked(bool Checked)
        {
            foreach (ListViewItem Item in this.listView1.Items)
            {
                Item.Checked = Checked;
            }
        }
        private void TextBoxKeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.A) && e.Control)
            {
                TextBox BoxOr = sender as TextBox;
                BoxOr.SelectAll();
            }
        }
        #endregion

        #region 事件
        private void Form_M_Load(object sender, EventArgs e)
        {
            IniForm();
            SetGrid(this.gridView1,this.gridControl1);
            SetGrid(this.gridView2, this.gridControl2);
            SetGrid(this.gridView3, this.gridControl3);
            this.gridView3.OptionsBehavior.ReadOnly = true;
            SetListView();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool IsEnable = ConnectDataBase();
            EnableButton(IsEnable);
            if (IsEnable)
            {
                //写入XML
                WriteIntoXml(this.comboBox1.Text.Trim());
                if (this.checkBox2.Checked)
                    GetTable_B_Click(null, null);
            }
        }

        private void GetTable_B_Click(object sender, EventArgs e)
        {
            this.TableName_L.Items.Clear();
            this.listBox1.Items.Clear();
            GetUseTable();
            IsBegin = true;
        }

        private void TableName_L_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsBegin)
            {
                this.listBox1.SelectedIndex = this.TableName_L.SelectedIndex;
                int Position = this.TableName_L.SelectedIndex;
                if (Position > -1)
                    this.textBox5.Text = string.Format(@"Select * From {0}", this.TableName_L.SelectedItem.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.GetGridInfo();
            this.gridControl1.DataSource = this.GridTable;
        }
        private void button3_Click(object sender, EventArgs e)
        {
            EditGrid();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您要删除该条数据吗？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                string ID = this.gridView1.GetFocusedRowCellValue("ID").ToString();
                if (ID != null)
                {
                    string UpdateSql = string.Format(@"Delete from Sys_GridCols
                        Where ID='{0}'", ID);
                    MyDb.pub_ExecBySqlText(UpdateSql);
                    DataRowView Del = (DataRowView)this.gridView1.GetFocusedRow();
                    Del.Delete();
                    this.GridTable.AcceptChanges();
                    this.label2.Text = System.DateTime.Now.ToString("hh-mm-ss") + ":有1条数据被删除";
                    UpdateGridVersion();
                }
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (AddGrid())
            {
                this.label2.Text = System.DateTime.Now.ToString("hh-mm-ss") + ":有1条GRID被增加";
                UpdateGridVersion();
            }
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                EditGrid();
            }
        }

        private void gridControl1_DoubleClick(object sender, EventArgs e)
        {
            DataRowView CurrentRow = (DataRowView)this.gridView1.GetFocusedRow();
            string GridID = CurrentRow["ID"].ToString();
            this.tabControl3.SelectedIndex = 1;
            this.GetGridColumnInfo(GridID);
            this.gridControl2.DataSource = this.GridColumnTable;
            this.label11.Text = GridID;
            //this.RestoreGridColumnInfo("Corpid", "CP001", this.gridView2);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            this.EditGridColumn();
        }

        private void TableName_L_DoubleClick(object sender, EventArgs e)
        {
            this.TableName_L.Enabled = false;
            int Index = this.TableName_L.SelectedIndex;
            if (Index > -1)
            {
                Object TablaName = this.TableName_L.SelectedItem;
                this.textBox2.Text = TablaName.ToString();
                GetTableField(TablaName.ToString());
                this.textBox5.Text = string.Format(@"Select * From {0}", TablaName.ToString());
            }
            this.TableName_L.Enabled = true;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (IsBegin)
            {
                ChangeListViewChecked(this.checkBox1.Checked);
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsBegin)
            {
                int Index = this.listView1.SelectedItems.Count;
                if (Index > 0)
                {
                    Index = this.listView1.SelectedItems[0].Index;
                    if (Index > -1)
                    {
                        ListViewItem Item = this.listView1.Items[Index];
                        this.textBox1.Text = Item.Text;
                        this.textBox3.Text = Item.SubItems[1].Text;

                    }
                }
            }
        }

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (IsBegin)
            {
                e.Item.ImageIndex = e.Item.Checked ? 1 : 0;                
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            this.Select_Text.Clear();
            if (this.listView1.CheckedItems.Count > 0)
            {
                string FrontName = this.textBox4.Text;
                if (this.checkBox8.Checked && this.checkBox10.Checked)
                {
                    this.Select_Text.AppendText("string ID = \"\";\r\n\r\n");
                }
                if (this.checkBox8.Checked)
                {
                    if (this.checkBox10.Checked)
                        this.Select_Text.AppendText("string Sql = string.Format(@\"");
                    else
                        this.Select_Text.AppendText("string.Format(@\"");
                }
                this.Select_Text.AppendText("Select ");
                bool IsFirst = true;
                foreach (ListViewItem Item in this.listView1.CheckedItems)
                {
                    if (!IsFirst)
                        this.Select_Text.AppendText("," + (FrontName.Length > 0 ? FrontName + "." + Item.Text : Item.Text) + "\r\n");
                    else
                    {
                        this.Select_Text.AppendText((FrontName.Length > 0 ? FrontName + "." + Item.Text : Item.Text) + "\r\n");
                        IsFirst = false;
                    }
                }
                if (this.textBox4.Text.Length > 0)
                    this.Select_Text.AppendText("From " + this.textBox2.Text + " As "+ FrontName + "\r\n");
                else
                    this.Select_Text.AppendText("From " + this.textBox2.Text + "\r\n");
                if (this.checkBox8.Checked)
                    this.Select_Text.AppendText("Where " + (FrontName.Length > 0 ? FrontName + "." : "") + "ID = '{0}'" + "\r\n");
                else
                    this.Select_Text.AppendText("Where " + (FrontName.Length > 0 ? FrontName + "." : "") + "ID = ''" + "\r\n");
                this.Select_Text.AppendText("Order by " + (FrontName.Length > 0 ? FrontName + "." : "") + "ID");
                if (this.checkBox9.Checked)
                    this.Select_Text.AppendText(" Desc");
                if (this.checkBox8.Checked)
                    this.Select_Text.AppendText("\",ID);");
                this.Select_Text.AppendText("\r\n");
                this.tabControl2.SelectedIndex = 2;
                this.tabControl4.SelectedIndex = 0;
            }
            else
                MessageBox.Show("需要选择列！");
        }

        private void button15_Click(object sender, EventArgs e)
        {
            this.Insert_Text.Clear();
            bool IsAdd = true;
            string FieldValue = "";
            string FieldName = "";
            bool IsFirst = true;

            if (this.listView1.CheckedItems.Count > 0)
            {
                int Counter = 0;
                if (this.checkBox3.Checked && this.checkBox11.Checked)
                {
                    foreach (ListViewItem Item in this.listView1.CheckedItems)
                    {
                        if (Item.SubItems[8].Text != "是")
                        {
                            if (this.textBox8.Text.Length > 0)
                                this.Insert_Text.AppendText("string " + Item.Text + " = " + this.textBox8.Text +";");
                            else
                                this.Insert_Text.AppendText("string " + Item.Text + " = \"\";");
                            if (Item.SubItems[1].Text != null)
                                this.Insert_Text.AppendText("//" + Item.SubItems[1].Text);
                            this.Insert_Text.AppendText("\r\n");
                        }
                    }
                }

                if (this.checkBox3.Checked)
                {
                    if (this.checkBox11.Checked)
                        this.Insert_Text.AppendText("\r\nstring Sql = string.Format(@\"");
                    else
                        this.Insert_Text.AppendText("string.Format(@\"");
                }
                this.Insert_Text.AppendText("Insert Into " + this.textBox2.Text + "(");
                IsFirst = true;
                foreach (ListViewItem Item in this.listView1.CheckedItems)
                {
                    if (Item.SubItems[8].Text != "是")
                    {
                        IsAdd = this.IsAddZone(Item.SubItems[2].Text);
                        if (!IsFirst)
                        {
                            this.Insert_Text.AppendText(",");
                            FieldValue += ",";
                        }
                        else
                        {
                            IsFirst = false;
                        }
                        this.Insert_Text.AppendText(Item.Text);
                        if (this.checkBox3.Checked)
                            FieldName += "," + Item.Text;
                        if (IsAdd)
                            FieldValue += "'{" + Counter.ToString() + "}'";
                        else
                            FieldValue += "{" + Counter.ToString() + "}";
                        Counter++;
                    }
                }
                this.Insert_Text.AppendText(")" + "\r\n" + "Values (");
                this.Insert_Text.AppendText(FieldValue + ")");
                if (this.checkBox3.Checked)
                    this.Insert_Text.AppendText("\"" + FieldName + ");");
                this.tabControl2.SelectedIndex = 2;
                this.tabControl4.SelectedIndex = 1;
            }
            else
                MessageBox.Show("需要选择列！");
        }

        private void button16_Click(object sender, EventArgs e)
        {
            this.Update_Text.Clear();
            bool IsAdd = true;
            string FieldValue = "";
            string FieldName = "";
            if (this.listView1.CheckedItems.Count > 0)
            {
                int Counter = 0;
                if (this.checkBox4.Checked && this.checkBox12.Checked)
                {
                    foreach (ListViewItem Item in this.listView1.CheckedItems)
                    {
                        if (Item.SubItems[8].Text != "是")
                        {
                            if (this.textBox9.Text.Length > 0)
                                this.Update_Text.AppendText("string " + Item.Text + " = " + this.textBox9.Text + ";");
                            else
                                this.Update_Text.AppendText("string " + Item.Text + " = \"\";");
                            if (Item.SubItems[1].Text != null)
                                this.Update_Text.AppendText("//" + Item.SubItems[1].Text);
                            this.Update_Text.AppendText("\r\n");
                        }
                    }
                }

                if (this.checkBox4.Checked)
                {
                    if (this.checkBox12.Checked)
                        this.Update_Text.AppendText("\r\nstring Sql = string.Format(@\"");
                    else
                        this.Update_Text.AppendText("string.Format(@\"");
                }

                this.Update_Text.AppendText("Update " + this.textBox2.Text + "\r\nSet ");
                bool IsFirst = true;
                foreach (ListViewItem Item in this.listView1.CheckedItems)
                {
                    if (Item.SubItems[8].Text != "是")
                    {
                        IsAdd = this.IsAddZone(Item.SubItems[2].Text);
                        if (!IsFirst)
                        {
                            this.Update_Text.AppendText(",");
                            FieldValue += ",";
                        }
                        else
                        {
                            IsFirst = false;
                        }
                        this.Update_Text.AppendText(Item.Text + "=");
                        if (this.checkBox4.Checked)
                            FieldName += "," + Item.Text;
                        if (IsAdd)
                        {
                            this.Update_Text.AppendText("'{" + Counter.ToString() + "}'");
                            FieldValue += "'{" + Counter.ToString() + "}'";
                        }
                        else
                        {
                            this.Update_Text.AppendText("{" + Counter.ToString() + "}");
                            FieldValue += "{" + Counter.ToString() + "}";
                        }
                        Counter++;
                    }
                }
                if (this.checkBox4.Checked)
                    this.Update_Text.AppendText("\"" + FieldName + ");");
                this.tabControl2.SelectedIndex = 2;
                this.tabControl4.SelectedIndex = 2;
            }
            else
                MessageBox.Show("需要选择列！");
        }

        private void button17_Click(object sender, EventArgs e)
        {
            this.Delete_Text.Clear();
            bool IsAdd = true;
            string FieldValue = "";
            string FieldName = "";
            if (this.listView1.CheckedItems.Count > 0)
            {
                int Counter = 0;
                if (this.checkBox5.Checked && this.checkBox13.Checked)
                {
                    foreach (ListViewItem Item in this.listView1.CheckedItems)
                    {
                        if (this.textBox10.Text.Length > 0)
                            this.Delete_Text.AppendText("string " + Item.Text + " = " + this.textBox10.Text + ";");
                        else
                            this.Delete_Text.AppendText("string " + Item.Text + " = \"\";");
                        if (Item.SubItems[1].Text != null)
                            this.Delete_Text.AppendText("//" + Item.SubItems[1].Text);
                        this.Delete_Text.AppendText("\r\n");
                    }
                }
                if (this.checkBox5.Checked)
                {
                    if (this.checkBox13.Checked)
                        this.Delete_Text.AppendText("\r\nstring Sql = string.Format(@\"");
                    else
                        this.Delete_Text.AppendText("string.Format(@\"");
                }

                this.Delete_Text.AppendText("Delete From " + this.textBox2.Text + "\r\nWhere ");
                bool IsFirst = true;
                foreach (ListViewItem Item in this.listView1.CheckedItems)
                {
                    IsAdd = this.IsAddZone(Item.SubItems[2].Text);
                    if (!IsFirst)
                    {
                        this.Delete_Text.AppendText(" And ");
                        FieldValue += ",";
                    }
                    else
                    {
                        IsFirst = false;
                    }
                    this.Delete_Text.AppendText(Item.Text + "=");
                    if (this.checkBox5.Checked)
                        FieldName += "," + Item.Text;
                    if (IsAdd)
                    {
                        this.Delete_Text.AppendText("'{" + Counter.ToString() + "}'");
                        FieldValue += "'{" + Counter.ToString() + "}'";
                    }
                    else
                    {
                        this.Delete_Text.AppendText("{" + Counter.ToString() + "}");
                        FieldValue += "{" + Counter.ToString() + "}";
                    }
                    Counter++;
                }
                if (this.checkBox5.Checked)
                    this.Delete_Text.AppendText("\"" + FieldName + ");");
                this.tabControl2.SelectedIndex = 2;
                this.tabControl4.SelectedIndex = 3;
            }
            else
                MessageBox.Show("需要选择列！");
        }

        private void button18_Click(object sender, EventArgs e)
        {
            this.button14.Enabled = false;
            this.button19.Enabled = true;
            IsStop = false;
            this.tabControl2.SelectedIndex = 2;
            this.tabControl4.SelectedIndex = 4;

            ArrayList FieldNameList = new ArrayList();
            ArrayList FieldTypeList = new ArrayList();
            ArrayList IsAddList = new ArrayList();
            foreach (ListViewItem Item in this.listView1.Items)
            {
                if (Item.SubItems[8].Text != "是")
                {
                    FieldNameList.Add(Item.Text);
                    FieldTypeList.Add(Item.SubItems[2].Text);
                    IsAddList.Add(this.IsAddZone(Item.SubItems[2].Text));
                }
            }

            this.Data_Text.Clear();
            if (this.checkBox6.Checked)
                this.Data_Text.AppendText("Delete From " + this.textBox2.Text + "\r\nGO\r\n");

            StringBuilder FieldNameSql = new StringBuilder();
            for (int Index = 0; Index < FieldNameList.Count; Index++)
                FieldNameSql.Append("," + FieldNameList[Index].ToString());

            DataTable CurrentTable = new DataTable();
            CurrentTable = MyDb.GetDataTable("Select * From " + this.textBox2.Text);
            this.progressBar2.Maximum = CurrentTable.Rows.Count;
            this.progressBar2.Visible = true;
            int Counter = 0;
            this.label9.Text = Counter.ToString();
            foreach (DataRow Row in CurrentTable.Rows)
            {
                if (!IsStop)
                {
                    this.Data_Text.AppendText(string.Format(@"Insert Into {0}(", this.textBox2.Text));
                    this.Data_Text.AppendText(FieldNameSql.ToString().Substring(1) + ")\r\nValues(");
                    for (int Index = 0; Index < FieldNameList.Count; Index++)
                    {
                        string FieldName = FieldNameList[Index].ToString();
                        if (Index > 0)
                            this.Data_Text.AppendText(",");

                        if (Convert.ToBoolean(IsAddList[Index]))
                        {
                            switch (FieldTypeList[Index].ToString())
                            {
                                case "datetime":
                                    if ((Row[FieldName] != null) && (Row[FieldName].ToString().Length > 0))
                                        this.Data_Text.AppendText("'" + Convert.ToDateTime(Row[FieldName]).ToString("yyyy-MM-dd hh:mm:ss") + "'");
                                    else
                                        this.Data_Text.AppendText("NULL");

                                    break;
                                case "bit":
                                    this.Data_Text.AppendText("'" + (Row[FieldName].ToString() == "True" ? "1" : "0") + "'");
                                    break;
                                default:
                                    this.Data_Text.AppendText("'" + Row[FieldName].ToString() + "'");
                                    break;
                            }
                        }
                        else
                            this.Data_Text.AppendText(Row[FieldName].ToString());
                    }

                    this.Data_Text.AppendText(")\r\nGO\r\n");
                    this.progressBar2.Value = Counter++;
                    this.label9.Text = Counter.ToString();
                    Application.DoEvents();
                    Thread.Sleep(0);
                }
                else
                {
                    break;
                }
            }
            this.progressBar2.Visible = false;
            FieldNameSql.Length = 0;
            CurrentTable.Dispose();
            FieldNameList.Clear();
            FieldTypeList.Clear();
            IsAddList.Clear();
            this.button14.Enabled = true;
            this.button19.Enabled = false;
        }

        private void button19_Click(object sender, EventArgs e)
        {
            IsStop = true;
            this.button14.Enabled = true;
            this.button19.Enabled = false;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //增加一条
            if (this.label11.Text != "无")
            {
                string ID, PareID, Num, SortNo, FieldName, FieldType, TitleRemark;
                ID = MyDb.pub_GetCounterId("GC");
                PareID = this.label11.Text;
                SortNo = "100";
                FieldName = "FieldName";
                FieldType = "varchar";
                TitleRemark = "TitleRemark";
                Num = ID + "_Colu" + SortNo;
                if (this.AddGridColu(ID, PareID, Num, SortNo, FieldName, FieldType, TitleRemark))
                {
                    GetGridColumnInfo(PareID);
                    UpdateGridVersion();
                    this.gridControl2.DataSource = this.GridColumnTable;
                    //this.gridView2.SetFocusedRowCellValue(gridColumn12, ID);
                    this.gridView2.FocusedRowHandle = this.gridView2.LocateByDisplayText(0, gridColumn12, ID);
                }
            }
            
        }

        private void button7_Click(object sender, EventArgs e)
        {
            DeleteGridColumn();
        }
        private void gridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteGridColumn();
            }
        }

        private void button20_Click(object sender, EventArgs e)
        {
            this.gridControl2.DataSource = null;
            string ID, PareID, Num, SortNo, FieldName, FieldType, TitleRemark;
            PareID = null;
            if (this.checkBox7.Checked)
            {
                MyDb.pub_ExecBySqlText(string.Format(@"Delete from Sys_GridCols
                    Where PareID='{0}'", this.label11.Text));
            }
            this.progressBar3.Visible = true;
            this.progressBar3.Maximum = this.listView1.CheckedItems.Count;
            int Counter = 0;
            foreach (ListViewItem Item in this.listView1.CheckedItems)
            {
                ID = MyDb.pub_GetCounterId("GC");
                PareID = this.label11.Text;
                SortNo = Counter.ToString();
                FieldName = Item.Text;
                FieldType = Item.SubItems[2].Text;
                TitleRemark = Item.SubItems[1].Text.Length > 0 ? Item.SubItems[1].Text : Item.Text;
                Num = ID + "_Colu" + SortNo;
                this.AddGridColu(ID, PareID, Num, SortNo, FieldName, FieldType, TitleRemark);
                this.progressBar3.Value = ++Counter;
                Application.DoEvents();
                Thread.Sleep(0);
            }
            this.progressBar3.Visible = false;
            if (this.listView1.CheckedItems.Count > 0)
            {
                GetGridColumnInfo(PareID);
                UpdateGridVersion();
                this.gridControl2.DataSource = this.GridColumnTable;
            }
        }

        private void tabControl2_Selected(object sender, TabControlEventArgs e)
        {
            int Index = this.tabControl2.SelectedIndex;
            switch (Index)
            {
                case 3:
                    int Position = this.TableName_L.SelectedIndex;
                    if (Position > -1)
                        this.textBox5.Text = string.Format(@"Select * From {0}", this.TableName_L.SelectedItem.ToString());
                    break;
                default:
                    break;
            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            SelectToData();
        }

        private void button22_Click(object sender, EventArgs e)
        {
            SelectToText();
        }

        private void button23_Click(object sender, EventArgs e)
        {
            this.tabControl2.SelectedIndex = 3;
            this.tabControl5.SelectedIndex = 0;
        }

        private void textBox5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                SelectToText();
            }
        }

        private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.comboBox1.Text.Trim().Length > 0)
                {
                    DialogResult Value = MessageBox.Show("贱人，您非要删除该连接字符串，不可吗？", "找打", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                    if (Value == DialogResult.OK)
                    {
                        DeleteFromXml(this.comboBox1.Text.Trim());
                        this.comboBox1.Items.Remove(this.comboBox1.Text.Trim());
                    }
                    this.comboBox1.SelectedIndex = this.comboBox1.Items.Count > 0 ? 0 : -1;
                    this.button1.Focus();
                }
            }
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            if (IsBegin)
            {
                string TableName = (sender as TextBox).Text;
                if (TableName.Length > 0)
                {
                    int Index = this.TableName_L.Items.IndexOf(TableName);
                    if (Index > -1)
                        this.TableName_L.SelectedIndex = Index;
                }
            }
        }

        private void button25_Click(object sender, EventArgs e)
        {
            //生成标识
            SetCreateCode();
        }
        private string GetSign(int index)
        {
            string returnValue;
            switch (index)
            {
                case -1:
                    returnValue = "?";
                    break;
                case 0:
                    returnValue = "!";
                    break;
                case 1:
                    returnValue = "@";
                    break;
                case 2:
                    returnValue = "#";
                    break;
                case 3:
                    returnValue = "$";
                    break;
                case 4:
                    returnValue = "%";
                    break;
                case 5:
                    returnValue = "^";
                    break;
                case 6:
                    returnValue = "&";
                    break;
                case 7:
                    returnValue = "*";
                    break;
                case 8:
                    returnValue = ">";
                    break;
                default:
                    returnValue = "<";
                    break;
            }
            return returnValue;
        }
        private void SetCreateCode()
        {
            this.text_create.Clear();
            if (this.listView1.CheckedItems.Count > 0)
            {
                int count = int.Parse(spinEdit1.Value.ToString());
                int index = -1;
                foreach (ListViewItem Item in this.listView1.CheckedItems)
                {
                    this.text_create.AppendText(GetSign(index));
                    for (int i = 0; i < count; i++)
                    {
                        this.text_create.AppendText(Item.Text + GetSign(i));
                    }
                    if (checkBox14.Checked)
                    {
                        this.text_create.AppendText(Item.SubItems[1].Text + GetSign(count + 1));
                    }
                    this.text_create.AppendText("\r\n");
                }
                this.tabControl2.SelectedIndex = 4;
            }
            else
                MessageBox.Show("需要选择列！");
        }
        private void button26_Click(object sender, EventArgs e)
        {
            SetCreateCode();
        }

        private void button24_Click(object sender, EventArgs e)
        {
            string GridId = this.gridView1.GetFocusedRowCellValue("ID").ToString();
            if (GridId != null)
            {
                Form_LikeAddGrid Like = new Form_LikeAddGrid();
                Like.DesGridId = GridId;
                if (Like.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    UpdateGridVersion();
                    MessageBox.Show("效仿增加完成!");
                }
                Like.Dispose();
            }
            
        }
        #endregion

    }
}
